<template>
    <view v-if="pageInit">
        <!--index.wxml-->
        <view class="trtc-demo-container">
            <view class="title" :style="'padding-top:' + ((headerHeight + statusBarHeight)/2 - 12) + 'px'">
                <view>VR带看</view>
            </view>
        </view>

        <view class="bottom-btn">
            <button class="btn" @tap="enterRoom" hover-class="none">进入VR带看</button>
        </view>
        <cover-image class="close" :style="'top:' + ((headerHeight + statusBarHeight) - 34) + 'rpx'"
            src="@/static/img/back.png" @tap="onBack"></cover-image>
    </view>
</template>

<script>
    import {
        mapState,
        mapMutations,
        mapActions
    } from 'vuex';
    const app = getApp();
    const App = app;
    let that = null
    const api = require("@/static/js/api.js")
    const utils = require("@/static/js/utils.js")
    export default {
        data() {
            return {
                pageInit: false,
                template: 'custom',//'1v1',
                debugMode: false,
                cloudenv: 'PRO',
                evnArray: [{
                    value: 'PRO',
                    title: 'PRO'
                }, {
                    value: 'CCC',
                    title: 'CCC'
                }, {
                    value: 'DEV',
                    title: 'DEV'
                }, {
                    value: 'UAT',
                    title: 'UAT'
                }],
                headerHeight: App.globalData.headerHeight,
                statusBarHeight: App.globalData.statusBarHeight,
                              
                roomObj:{
                    projectId: 'default',
                    roomId: '',
                    ownerId:'',
                    roomType: 'audio',
                    userId: '',
                }              
            };
        },
        computed: {
            ...mapState({
                hasLogin: state => state.userInfo.hasLogin,
                isAuthPhone: state => state.userInfo.isAuthPhone,
                isAuthUserInfo: state => state.userInfo.isAuthUserInfo, 
                isSeller: state => state.userInfo.isSeller,
                sellerObj: state => state.userInfo.sellerObj,
                buyerObj: state => state.userInfo.buyerObj,
                shopInfo: state => state.userInfo.shopInfo,
            }),
        },
        
        components: {},
        props: {},
        /*
            所有带看都是进这个页面，
            分享链接，只需要这两个参数 ownerId  roomId
            pages/trtcRoom/videochat/index?
            ownerId=1497129347918635009
            &roomId=100059508
        */
        onLoad: function(options) {
            that = this;
            //=== 管理员且是自己分享的链接时，切成置业顾问模式
            if (that.isSeller&&(that.sellerObj.uuid==options.ownerId)){
                uni.setStorageSync("userType", 1)
            }else{
                uni.setStorageSync("userType", 0)
            }
            
            //===如果ownerId不存在，默认使用，归属销售的id
            if (uni.getStorageSync("userType") == 0){
                if (options.ownerId){
                    that.roomObj.ownerId = options.ownerId ||'';
                }else{
                    that.roomObj.ownerId = that.buyerObj.salesmanId
                }
            }else{
                that.roomObj.ownerId = options.ownerId || that.sellerObj.uuid;
            }
                                       
            that.roomObj.projectId= wx.getStorageSync("projectId");
            

            if (options.roomId) {
                this.roomObj.roomId = options.roomId;
            } else {
                this.roomObj.roomId = that.roomObj.projectId + Math.floor(1e5 * Math.random()).toString();
            }
            
            // if (options.type) {
            //     this.roomObj.roomType = options.type;
            // } 
            
            //===其实，是同一个
            if (uni.getStorageSync("userType") == 0){
                this.roomObj.userId = that.buyerObj.uuid;    
            }else{
                this.roomObj.userId = that.sellerObj.uuid;
            }
            
            that.enterRoom();
        },
        
        
        methods: {           
            ...mapMutations(['setUserInfo', 'setLoginStatus', 'setUserId']),
      
            checkEnterRoomParam(){
                const nowTime = new Date();
                if (nowTime - this.tapTime < 1000) {
                    return;
                } 
                var roomId = this.roomObj.roomId;
                if (!roomId) {
                	wx.showToast({
                		title: '房间号为空',
                		icon: 'none',
                		duration: 2000,
                	})
                	return false
                }
                if (/^\d*$/.test(roomId) === false) {
                	wx.showToast({
                		title: '房间号只能为数字',
                		icon: 'none',
                		duration: 2000,
                	})
                	return false
                }
                if (roomId > 4294967295 || roomId < 1) {
                	wx.showToast({
                		title: '房间号取值范围为 1~4294967295',
                		icon: 'none',
                		duration: 2000,
                	})
                	return false
                }
                this.tapTime = nowTime;
                return true
            },
            
            postMessageByWechatOfficialVR(){

                //===是顾客才发送带看              
                if (uni.getStorageSync('userType')==0){   
                    var	curTime = Date.parse(new Date());
                    curTime /= 1e3
                    var path = '/pages/home/home?projectId='+uni.getStorageSync("projectId")+'&userType=1'
                    var param={
                        roomId: that.roomObj.roomId,
                        ownerId: that.roomObj.ownerId,
                        time: curTime,
                    }
                    var sharePath =  '/pages/trtcRoom/videochat/index?'+ utils.KeyValueToUrl(param);
                    
                    path = path + '&sharePath=' + encodeURIComponent(sharePath)
                    
                    api.postMessageByWechatOfficial({
                        param: {
                            type: 'VR',
                            messageId: '',//====ID为空，会不过滤相同请求
                            page: path,
                            salesmanId: that.roomObj.ownerId,
                        }
                    }).then(res => {
                        console.log(res)
                        if (res.success) {  
                            
                        }
                    })
                }
            },
            
            enterRoom: function() {
                if (!that.checkEnterRoomParam()){
                    that.pageInit = true
                    return;
                }
                console.log("准备进入房间:",that.roomObj)

                that.checkDeviceRecordAuthorize().then(result => {
                    
                    
                    
                    var paramObj = {
                        roomID: that.roomObj.roomId,
                        userID: that.roomObj.userId,
                        ownerId: that.roomObj.ownerId,
                        projectId: that.roomObj.projectId,                  
                        isTakeLook: true,  //==带看
                        template: that.template,
                        debugMode: that.debugMode,
                        // cloudenv: that.cloudenv,
                        role: 'presenter',
                        audioVolumeType: 'voicecall',
                    }
                    const url = './webRoom?'+ utils.KeyValueToUrl(paramObj)
                    that.postMessageByWechatOfficialVR();
                    console.log('授权成功', result);
                    that.pageInit = true
                    uni.redirectTo({
                        url: url
                    });
                }).catch(error => {
                    that.pageInit = true
                    console.log('没有授权', error);
                });
                
            },
            //===只授权麦克风
            checkDeviceRecordAuthorize: function() {
                this.hasOpenDeviceAuthorizeModal = false;
                return new Promise((resolve, reject) => {
                    if (!wx.getSetting || !wx.getSetting()) {
                        // 微信测试版 获取授权API异常，目前只能即使没授权也可以通过
                        resolve();
                    }
            
                    wx.getSetting().then(result => {
                        console.log('getSetting', result);
                        this.authorizeMic = result.authSetting['scope.record'];
        
                        if (result.authSetting['scope.record']) {
                            // 授权成功
                            resolve();
                        } else {
                            // 没有授权，弹出授权窗口
                            // 注意： wx.authorize 只有首次调用会弹框，之后调用只返回结果，如果没有授权需要自行弹框提示处理
                            console.log('getSetting 没有授权，弹出授权窗口', result);
                            wx.authorize({
                                scope: 'scope.record'
                            }).then(res => {
                                console.log('authorize mic', res);
                                this.authorizeMic = true;
                                resolve();
                            }).catch(error => {
                                console.log('authorize mic error', error);
                                this.authorizeMic = false;
                                this.openRecordConfirm();
                                reject(new Error('authorize fail'));
                            });
                        }
                    });
                });
            },
            
            openRecordConfirm: function() {
                if (this.hasOpenDeviceAuthorizeModal) {
                    return;
                }
            
                this.hasOpenDeviceAuthorizeModal = true;
                return wx.showModal({
                    content: '您没有打开麦克风的权限，是否去设置打开？',
                    confirmText: '确认',
                    cancelText: '取消',
                    success: res => {
                        this.hasOpenDeviceAuthorizeModal = false;
                        console.log(res); // 点击“确认”时打开设置页面
            
                        if (res.confirm) {
                            console.log('用户点击确认');
                            wx.openSetting({
                                success: res => {}
                            });
                        } else {
                            console.log('用户点击取消');
                        }
                    }
                });
            },
            
            
            
            
            checkDeviceRecordAndCameraAuthorize: function() {
                this.hasOpenDeviceAuthorizeModal = false;
                return new Promise((resolve, reject) => {
                    if (!wx.getSetting || !wx.getSetting()) {
                        // 微信测试版 获取授权API异常，目前只能即使没授权也可以通过
                        resolve();
                    }

                    wx.getSetting().then(result => {
                        console.log('getSetting', result);
                        this.authorizeMic = result.authSetting['scope.record'];
                        this.authorizeCamera = result.authSetting['scope.camera'];

                        if (result.authSetting['scope.camera'] && result.authSetting[
                            'scope.record']) {
                            // 授权成功
                            resolve();
                        } else {
                            // 没有授权，弹出授权窗口
                            // 注意： wx.authorize 只有首次调用会弹框，之后调用只返回结果，如果没有授权需要自行弹框提示处理
                            console.log('getSetting 没有授权，弹出授权窗口', result);
                            wx.authorize({
                                scope: 'scope.record'
                            }).then(res => {
                                console.log('authorize mic', res);
                                this.authorizeMic = true;

                                if (this.authorizeCamera) {
                                    resolve();
                                }
                            }).catch(error => {
                                console.log('authorize mic error', error);
                                this.authorizeMic = false;
                            });
                            wx.authorize({
                                scope: 'scope.camera'
                            }).then(res => {
                                console.log('authorize camera', res);
                                this.authorizeCamera = true;

                                if (this.authorizeMic) {
                                    resolve();
                                } else {
                                    this.openConfirm();
                                    reject(new Error('authorize fail'));
                                }
                            }).catch(error => {
                                console.log('authorize camera error', error);
                                this.authorizeCamera = false;
                                this.openConfirm();
                                reject(new Error('authorize fail'));
                            });
                        }
                    });
                });
            },

            
            openConfirm: function() {
                if (this.hasOpenDeviceAuthorizeModal) {
                    return;
                }

                this.hasOpenDeviceAuthorizeModal = true;
                return wx.showModal({
                    content: '您没有打开麦克风和摄像头的权限，是否去设置打开？',
                    confirmText: '确认',
                    cancelText: '取消',
                    success: res => {
                        this.hasOpenDeviceAuthorizeModal = false;
                        console.log(res); // 点击“确认”时打开设置页面

                        if (res.confirm) {
                            console.log('用户点击确认');
                            wx.openSetting({
                                success: res => {}
                            });
                        } else {
                            console.log('用户点击取消');
                        }
                    }
                });
            },
            onBack: function() {
                wx.navigateBack({
                    delta: 1
                });
            }
        }
    };
</script>
<style>
    /**index.wxss**/

    .trtc-demo-container {
        background-image: url("https://mc.qcloudimg.com/static/img/7da57e0050d308e2e1b1e31afbc42929/bg.png");
        background-color: #333;
        background-repeat: no-repeat;
        background-size: cover;
        width: 100vw;
        height: 100vh;
        display: flex;
        flex-direction: column;
        align-items: center;
        box-sizing: border-box;
    }

    .trtc-demo-container .title {
        color: #FFFFFF;
        padding-top: 65rpx;
        line-height: 60rpx;
    }

    .trtc-demo-container .input-box {
        background-color: transparent;
        color: #ffffff;
        padding: 2vw 5vw 1vw;
        border-bottom: 1px solid #577785;
        margin: 100rpx 0 40rpx 0;
        text-align: center;
        box-sizing: border-box;
        width: 80vw;
    }

    .trtc-demo-container .input-box input {
        font-size: 20px;
    }

    .choice-content {
        margin-top: 20rpx;
        width: 80vw;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        flex-wrap: wrap;
        font-size: 14px;
        color: #ffffff;
    }

    .choice-content switch {
        color: #006eff;
        transform: scale(0.8);
    }


    .bottom-btn {
        position: fixed;
        width: 100vw;
        text-align: center;
        bottom: 5vh;
    }

    .bottom-btn .btn {
        width: 80%;
        background-color: #006eff;
        border-radius: 50px;
        color: #ffffff;
    }

    .close {
        position: absolute;
        padding-left: 5vw;
        padding-right: 5vw;
        width: 50rpx;
        height: 60rpx;
    }
</style>
